package com.qianzhou.config;

import com.qianzhou.pojo.Configuration;
import com.qianzhou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ClassName XMLMapperBuild
 * @Description TODO
 * @Author zhouqian
 * @Date 2022/1/15 8:56 PM
 * @Version 1.0
 */

public class XMLMapperBuild {
    private Configuration configuration;
    public XMLMapperBuild(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.selectNodes("//select");
        String namespace = rootElement.attributeValue("namespace");
        for (Element element: elements
             ) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            String key = namespace+"."+id;
            configuration.getMappedStatement().put(key,mappedStatement);
        }
    }
}
